package com.flowershop.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/shop/*")
public class AuthFilter implements Filter {
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String path = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        
        // 不需要登录的路径
        if (path.equals("/shop") || path.equals("/shop/login") || path.startsWith("/shop/static/")) {
            chain.doFilter(request, response);
            return;
        }
        
        // 检查是否已登录
        Object user = httpRequest.getSession().getAttribute("user");
        if (user == null) {
            // AJAX请求返回JSON
            if ("XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With"))) {
                httpResponse.setContentType("application/json;charset=UTF-8");
                httpResponse.getWriter().write("{\"success\":false,\"message\":\"请先登录\"}");
            } else {
                // 普通请求重定向到登录页
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/shop/login");
            }
            return;
        }
        
        chain.doFilter(request, response);
    }
} 